package cn.tanglong.pet.service.impl;

import cn.tanglong.basic.exception.MyException;
import cn.tanglong.basic.service.impl.BaseServiceImpl;
import cn.tanglong.basic.util.AjaxResult;
import cn.tanglong.basic.util.PageList;
import cn.tanglong.pet.domain.Pet;
import cn.tanglong.pet.domain.PetDetail;
import cn.tanglong.pet.mapper.PetDetailMapper;
import cn.tanglong.pet.mapper.PetMapper;
import cn.tanglong.pet.query.PetQuery;
import cn.tanglong.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void add(Pet pet) {
        petMapper.add(pet);
        PetDetail detail = pet.getDetail();
        detail.setPet_id(pet.getId());
        petDetailMapper.add(detail);
    }

    /**
     * 上架
     * 判断参数、id不为空
     * 判断宠物状态：上下架
     * 更改宠物状态
     */
    @Override
    public void onsale(List<Long> ids) {
        // 先判断参数和id不为空
        if(ids ==null || ids.size()==0){
            throw new MyException("id为空！");
        }
        // 批量查询下架宠物
        List<Pet> pets = petMapper.batchSelectByIds(ids,Pet.STATE_OFFLINE);
        // 获取一个时间对象
        Date now = new Date();
        // 用循环设置上架时间,状态，然后修改数据库上架
        pets.forEach(pet -> {
            pet.setState(Pet.STATE_ONLINE);
            pet.setOnsaletime(now);
            petMapper.update(pet);
        });
    }

    /**
     * 下架
     *
     * @param 通过id下架
     */
    @Override
    public void offsale(List<Long> ids) {
// 先判断参数和id不为空
        if(ids ==null || ids.size()==0){
            throw new MyException("id为空！");
        }
        // 批量查询上架宠物
        List<Pet> pets = petMapper.batchSelectByIds(ids,Pet.STATE_ONLINE);
        // 获取一个时间对象
        Date now = new Date();
        // 用循环设置下架时间,状态，然后修改数据库下架
        pets.forEach(pet -> {
            pet.setState(Pet.STATE_OFFLINE);
            pet.setOnsaletime(now);
            petMapper.update(pet);
        });
    }

    @Override
    public Pet selectOnLineById(Long id) {
        return petMapper.selectByIdAndState(id,Pet.STATE_ONLINE);
    }


}
